package gui.newgui.assignedplayerspanel;

import gui.newgui.IController;

import java.util.Observable;
import java.util.Observer;

import table.models.ParticipantsTableModel;
import tournamentData.TournamentData;

import com.sun.org.apache.xpath.internal.functions.WrongNumberArgsException;

import core.Person;
import db.newversion.ArchersDB;

public class AssignedPlayersController implements IController, Observer {
	private final AssignedPlayersPanel window;

	public AssignedPlayersController(AssignedPlayersPanel window) {
		this.window = window;
		ArchersDB.getInstance().addObserver(this);
		TournamentData.getInstance().addObserver(this);
	}

	@Override
	public void updateTable() {
		if (TournamentData.getInstance().getAllParticipants().length > 0) {
			ParticipantsTableModel participantsTableModel = (ParticipantsTableModel) this.window.getTable().getModel();
			participantsTableModel.removeData();
			for (int i = 0; i < TournamentData.getInstance().getAllParticipants().length; i++) {
				try {
					Person toAdd = ArchersDB.getInstance().getElement(TournamentData.getInstance().getAllParticipants() [i]);
					participantsTableModel.addRow(new Object [] { TournamentData.getInstance().getAllParticipants() [i], toAdd.getName(), toAdd.getSurName(), toAdd.getNation(), toAdd.getCountry(),
							toAdd.getBowCathegory(), toAdd.getAgeClass(), toAdd.getClub(), toAdd.getGender(), toAdd.isLicense(), toAdd.isCountryRating(), toAdd.getBirthdate() });
				} catch (WrongNumberArgsException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			participantsTableModel.fireTableDataChanged();
		} else {
			ParticipantsTableModel participantsTableModel = (ParticipantsTableModel) this.window.getTable().getModel();
			participantsTableModel.removeData();
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		this.updateTable();
	}
}
